package com.tg.app.activity.device.add;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.appbase.custom.constant.CommonConstants;
import com.tange.module.add.lan.DeviceLanSearch;
import com.tg.app.R;
import com.base.BaseFragment;
import com.tg.app.listener.OnAddDeviceListener;
import com.tg.app.util.LogUtils;
import com.tg.app.widget.CircleView;
import com.tange.base.toolkit.PreferenceUtil;
import com.tg.appcommon.android.TGAlertDialog;

import java.util.ArrayList;
import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 * create an instance of this fragment.
 */
public class LanSearchFragment extends BaseFragment {

    public static final String TAG = "LanSearchFragment";
    private CircleView circleView;

    private ArrayList<String> snList ;
    private  static  final  int  SEARCH = 0x01;
    private boolean complete  = false;
    public  static  final  String  EXT_LAN_SEARCH_RESULT= "ext_lan_search_result";

    private DeviceLanSearch deviceLanSearch;

    private final Handler  handler = new Handler(new Handler.Callback() {
        @SuppressLint("DefaultLocale")
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what ==SEARCH){
                if (deviceLanSearch != null) {
                    deviceLanSearch.stop();
                }
                circleView.stopAnim();
                if (snList.size()>0){
                    if (listener!=null){
                        Bundle args  = new Bundle();
                        args.putStringArrayList(EXT_LAN_SEARCH_RESULT,snList);
                        listener.onSearchDevice(args);
                    }
                }else {
                    LogUtils.uploadLogN("LanSearch",String.format("用户ID：%d，进行一次有线搜索，未搜索到设备", PreferenceUtil.getInt(getContext(), CommonConstants.PRE_USER_ID)));
                    new TGAlertDialog(mActivity).builder().setMessage(R.string.not_lan_device).setPositiveButton(R.string.search_again, v -> searchDevice()).setNegativeButton(getString(R.string.cancel), v -> mActivity.finish()).show();
                }
            }
            return false;
        }
    });
    private OnAddDeviceListener listener;

    public void setListener(OnAddDeviceListener listener) {
        this.listener = listener;
    }

    public LanSearchFragment() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        snList = new ArrayList<>();

        deviceLanSearch = DeviceLanSearch.create(getContext(), new DeviceLanSearch.Callback() {
            @Override
            public void onRefresh(List<String> deviceList) {
                snList.clear();
                snList.addAll(deviceList);

                if (!complete){
                    handler.removeMessages(SEARCH);
                    handler.sendEmptyMessageDelayed(SEARCH,1000);
                    complete = true;
                }
            }

            @Override
            public void onSearchTimeout() {
                if (!complete){
                    handler.removeMessages(SEARCH);
                    handler.sendEmptyMessageDelayed(SEARCH,1000);
                    complete = true;
                }
            }
        });
        searchDevice();
    }
    public void searchDevice(){
        complete  = false;
        circleView.startAnim();
        deviceLanSearch.start();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        deviceLanSearch.stop();
        handler.removeMessages(SEARCH);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View  view =  inflater.inflate(R.layout.fragment_lan_search, container, false);
        // Inflate the layout for this fragment
        circleView = view.findViewById(R.id.circle_view);
        return view;
    }

}
